/*
 * @author ${user}
 * @date ${year}-${month}-${day}
 */

package net.xdclass.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.RabbitMQConfig;
import net.xdclass.constant.TimeConstant;
import net.xdclass.controller.request.ConfirmOrderRequest;
import net.xdclass.controller.request.ProductOrderPageRequest;
import net.xdclass.enums.*;
import net.xdclass.exception.BizException;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.manager.ProductManager;
import net.xdclass.manager.ProductOrderManager;
import net.xdclass.mapper.ProductOrderMapper;
import net.xdclass.model.EventMessage;
import net.xdclass.model.ProductDO;
import net.xdclass.model.ProductOrderDO;
import net.xdclass.service.ProductOrderService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.util.JsonUtil;
import net.xdclass.vo.PayInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 二当家小D
 * @since 2025-09-23
 */
@Service
public class ProductOrderServiceImpl extends ServiceImpl<ProductOrderMapper, ProductOrderDO> implements ProductOrderService {
    @Autowired
	private ProductOrderManager productOrderManager;
	@Autowired
	private ProductManager productManager;
	@Autowired
	private RabbitTemplate rabbitTemplate;
	@Autowired
	private RabbitMQConfig rabbitMQConfig;

	@Override
	public String queryState(String outTradeNo) {
		Long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
		ProductOrderDO productOrderDO = productOrderManager.findByOutTradeNoAndAccountNo(outTradeNo,accountNo);
		if( productOrderDO != null){
			return productOrderDO.getState();
		}
		return null;
	}

	@Override
	public Map<String, Object> getPage(ProductOrderPageRequest productOrderPageRequest) {
		Long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
		int page = productOrderPageRequest.getPage();
		int size = productOrderPageRequest.getSize();
		String state = productOrderPageRequest.getState();
		Map <String,Object> map = productOrderManager.page(page,size,accountNo,state);
		return map;
	}

	@Override
	public JsonData confirmOrder(ConfirmOrderRequest confirmOrderRequest, HttpServletResponse response){
		Long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
		String nickname =LoginInterceptor.threadLocal.get().getUsername();
    // 验证价格
		Long productId = confirmOrderRequest.getProductId();
		ProductDO productDO = productManager.detail(productId);
	    checkPrice(confirmOrderRequest,productDO);

	//  生成订单编号
		String orderOutTradeNo = CommonUtil.getStringNumRandom(32);
    //  创建订单
		ProductOrderDO productOrderDO = ProductOrderDO.builder().productId(confirmOrderRequest.getProductId())
				.productTitle(productDO.getTitle()).productAmount(productDO.getAmount())
				.productSnapshot(JsonUtil.obj2Json(productDO)).buyNum(confirmOrderRequest.getBuyNum())
				.outTradeNo(orderOutTradeNo).state(ProductOrderStateEnum.NEW.name())
				.totalAmount(confirmOrderRequest.getTotalAmount())
				.payType(confirmOrderRequest.getPayType()).nickname(nickname)
				.accountNo(accountNo).del(0).billType(confirmOrderRequest.getBillType())
				.billHeader(confirmOrderRequest.getBillHeader())
				.billContent(confirmOrderRequest.getBillContent())
				.billReceiverPhone(confirmOrderRequest.getBillReceiverPhone())
				.billReceiverEmail(confirmOrderRequest.getBillReceiverEmail()).build();
		productOrderManager.add(productOrderDO);



	//  创建支付对象
		PayInfoVO payInfoVO = PayInfoVO.builder().accountNo(accountNo)
				.outTradeNo(orderOutTradeNo).clientType(confirmOrderRequest.getClientType())
				.payType(confirmOrderRequest.getPayType()).title(productDO.getTitle()).description("")
				.payFee(confirmOrderRequest.getPayAmount()).orderPayTimeoutMills(TimeConstant.ORDER_PAY_TIMEOUT_MILLS)
				.build();
	 // 发送延迟消息
		EventMessage eventMessage =EventMessage.builder()
				.eventMessageType(EventMessageType.PRODUCT_ORDER_NEW.name())
				.accountNo(accountNo)
				.bizId(orderOutTradeNo)
				.build();
		rabbitTemplate.convertAndSend(rabbitMQConfig.getOrderEventExchange(),rabbitMQConfig.getOrderCloseDelayRoutingKey(),eventMessage);
		return  JsonData.buildSuccess();
	}

	@Override
	public void closeProductOrder(EventMessage eventMessage) {
		//查询数据库里订单是否被支付
		String outTradeNo = eventMessage.getBizId();
		long   accountNo = eventMessage.getAccountNo();
		ProductOrderDO productOrderDO = productOrderManager.findByOutTradeNoAndAccountNo(outTradeNo,accountNo);
		if(productOrderDO != null ){
			log.warn("订单不存在" );
		}
		String state= productOrderDO.getState();

		//数据库中订单支付成功，什么都不用做
		if(state.equalsIgnoreCase(ProductOrderStateEnum.PAY.name())){

		}
		//数据库中支付不成功，查询第三番个支付消息判断是否支付成功
		if(state.equalsIgnoreCase(ProductOrderStateEnum.NEW.name())){

		}

		//第三方支付成功，将数据库中订单信息更新为已支付

		//第三方支付不成功，关闭订单

	}

	private void checkPrice(ConfirmOrderRequest confirmOrderRequest,ProductDO productDO){
		BigDecimal productsum = productDO.getAmount().multiply(BigDecimal.valueOf(confirmOrderRequest.getBuyNum()));
		BigDecimal ordersum = confirmOrderRequest.getTotalAmount();
		if (productsum.compareTo(ordersum) != 0){
			throw new BizException(BizCodeEnum.ORDER_CONFIRM_PRICE_FAIL);
		}
	}
}
